<template>
  <div>
    <el-form @submit.native.prevent :inline="true">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="主本名称"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <select-farm-org
          v-model="params['org_class.eq']"
          placeholder="主体类型"
          clearable
          @change="getData()"
          class="form-control-ml"
        ></select-farm-org>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="startDate"
          placeholder="申请起始时间"
          class="form-control-ml"
          @change="dateChange"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="endDate"
          placeholder="申请截止时间"
          class="form-control-ml"
          @change="dateChange"
          type="date"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item>
        <select-product
          clearable
          class="form-control-ml"
          v-model="params['project_type_id.eq']"
          placeholder="选择贷款产品"
          @change="productChange()"
        ></select-product>
      </el-form-item> -->
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      ref="table"
      name="table"
      class="table-sm"
      row-key="credit_id"
      :columns="tableColumns"
      :data="tableData"
      @selection-change="handleSelectionChange"
    ></c-table>

    <div class="query-pagination">
      <div class="d-flex px-3 align-items-center">
        <div class="text-muted">
          已选择
          <span class="text-info">{{ selectLen }}</span>
          个项目
        </div>
        <el-button type="text" class="py-0" v-if="selectLen" @click="handleSelectionClear">
          清空选择
        </el-button>
      </div>
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size.sync="params.size"
        :total="totalCount"
        :page-sizes="[15, 50, 100, 500]"
        @size-change="handleSizeChange"
        @current-change="getData"
      ></el-pagination>
    </div>

    <div class="mt-3 text-center">
      <el-button type="primary" class="btn-long" @click="handleRecommend">推荐</el-button>
      <el-button class="btn-long" @click="handleDismiss">取消</el-button>
    </div>

    <el-dialog
      title="项目推荐"
      :visible.sync="confirmVisible"
      :close-on-click-modal="false"
      append-to-body
      width="500px"
    >
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">项目数量：</div>
        <div class="col-8">{{ selectLen }} 个</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">申请总额：</div>
        <div class="col-8">{{ totalFunds }} 万元</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">推荐人员：</div>
        <div class="col-8">{{ userName }}</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">推荐日期：</div>
        <div class="col-8">{{ submitTime }}</div>
      </div>
      <div class="text-center mt-5">
        <el-button
          type="primary"
          class="btn-long"
          :loading="submitLoading"
          @click="handleRecommendSubmit"
        >
          确认推荐
        </el-button>
        <el-button class="btn-long" :disabled="submitLoading" @click="confirmVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
    <view-dialog :visible.sync="viewVisible" :is-class="isClass" :query-id="queryId"></view-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { strip, dateFormat } from '@vimi/utils-tool'

import SelectAddress from '@/components/select/SelectAddress'
import SelectFarmOrg from '@/components/select/SelectFarmOrg'
import ViewDialog from '@/gov/views/bus/track/ViewDialog'

export default {
  components: {
    SelectAddress,
    SelectFarmOrg,
    ViewDialog,
    // SelectProduct,
  },
  props: {
    businessCode: String,
  },
  data() {
    return {
      params: {
        index: 1,
        size: 15,
        customer_name: '',
        'submit_person.eq': '',
        'recommend_status.eq': 0,
      },
      order: {
        create_time: 'DESC',
      },
      loading: false,
      totalCount: 0,
      tableData: [],
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            width: 55,
            reserveSelection: true,
          },
        },
        { attrs: { label: '主体名称', prop: 'customer_name' } },
        { attrs: { label: '经营地址', prop: 'address' } },
        { attrs: { label: '主体类型', prop: 'org_class_name' } },
        { attrs: { label: '联系人', prop: 'corp_name' } },
        { attrs: { label: '联系电话', prop: 'mobile_no' } },
        { attrs: { label: '统一社会信用代码', prop: 'register_no' } },
        { attrs: { label: '申请金额', prop: 'apply_funds' } },
        { attrs: { label: '资金用途', prop: 'funds_use_dir' } },
        { attrs: { label: '申请时间', prop: 'create_time' } },
        {
          attrs: { label: '操作', align: 'center', width: 100 },
          operations: [{ content: '查看', icon: 'fa fa-search', event: this.handleView }],
        },
      ],

      // 选择
      multipleSelection: [],

      // 推荐
      submitLoading: false,
      confirmVisible: false,
      totalFunds: 0,
      submitTime: '',

      // 选择担保机构
      isSelectCredit: false,
      selectedOrgCredit: {},

      // 选择银行
      startDate: '',
      endDate: '',
      queryId: '',
      isClass: false,
      viewVisible: false,
    }
  },
  computed: {
    ...mapGetters(['userId', 'user']),
    selectLen() {
      return this.multipleSelection.length
    },
    userName() {
      return this.user.realName
    },
    queryAddressCode() {
      return this.user.queryAddressCode || this.user.addressCode
    },
  },
  watch: {
    businessCode: {
      handler: function () {
        if (!this.businessCode) {
          return
        }
        this.params['main_business_code.eq'] = this.businessCode
        this.getData()
      },
      immediate: true,
    },
  },
  created() {
    this.params.address_code = this.queryAddressCode
  },
  mounted() {},
  methods: {
    productChange() {
      this.clearSelect()
      this.getData()
    },

    dateChange() {
      this.params['create_time.gte'] = this.startDate || ''
      this.params['create_time.lte'] = this.endDate ? this.endDate + ' 23:59:59' : ''
      this.getData()
    },
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData({
          table: 'credit_industrial',
          params: this.params,
          order: this.order,
        })
        .then(res => {
          const data = res?.data ?? {}
          this.tableData = data.data ?? []
          this.totalCount = data.totalCount ?? 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleView(row = {}) {
      this.queryId = row.credit_id
      this.isClass = +row.credit_type === 1
      this.viewVisible = true
    },
    handleSizeChange(val) {
      // this.clearSelect()
      this.params.size = val
      this.getData(1)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSelectionClear() {
      this.clearSelect()
    },
    handleRecommend() {
      if (!this.selectLen) {
        return this.$message.error('请先选择项目')
      }
      // 项目总额
      let totalFunds = 0
      for (const project of this.multipleSelection) {
        totalFunds += +project.apply_funds || 0
      }
      this.totalFunds = strip(totalFunds)
      this.submitTime = dateFormat(new Date(), 'yyyy年MM月dd日')

      this.confirmVisible = true
    },
    handleRecommendSubmit() {
      this.$confirm('确定认推荐?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          this.submitLoading = true
          const data = this.multipleSelection.map(it => {
            const item = {
              recommend_status: 1,
              recommend_time: this.$utils.dateFormat(new Date()),
              recommend_person: this.userName,
              credit_industrial_id: it.credit_industrial_id,
            }
            return item
          })
          return this.$api.updateBatch(this.$serviceName, 'credit_industrial', data)
        })
        .then(res => {
          this.$message.success('推荐成功')
          this.clearSelect()
          this.confirmVisible = false
          this.getData()
          this.$emit('success', res)
        })
        .catch(err => {
          if (err !== 'cancel') {
            this.$message.error('推荐失败，请重试！')
            throw err
          }
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    clearSelect() {
      const $tableRef = this.$refs.table.$refs.table
      if (!$tableRef) return
      $tableRef.clearSelection()
    },
    handleDismiss() {
      this.$emit('dismiss')
    },
  },
}
</script>

<style lang="scss" scoped></style>
